//
//  ShareDeviceManageViewController.m
//  SenMo
//
//  Created by ZengYuan on 15/12/23.
//  Copyright © 2015年 ZengYuan. All rights reserved.
//

#import "ShareDeviceManageViewController.h"
#import "UserUnit.h"
#import "ShareUserCell.h"
#import "SettingCell.h"
#import "ShowSetCell.h"
#import "SwitchSetCell.h"
#import "InputShareUserViewController.h"
#import "AllShareUsersTableViewController.h"
#import "TimeRuleViewController.h"
#import "DeviceHandle.h"
#import "SetShareUserAdminViewController.h"
#import "RequestViewController.h"

@interface ShareDeviceManageViewController ()
{
    NSMutableArray *dataArray;
    
    float shareUsers_height;
}
@end

@implementation ShareDeviceManageViewController
@synthesize tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - NAVBARHEIGHT_STATUSBAR);
    
    tableView = [[UITableView alloc]initWithFrame:rect
                                            style:UITableViewStylePlain];
    tableView.backgroundColor = MAIN_DARKCOLOR;
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
    dataArray = [NSMutableArray array];
    [self getShareUsersHeight];
    
    if (self.device.value == 1) {
        //管理员，获取时间规则
        
         __weak typeof(self) weakSelf = self;
        [DeviceHandle deviceGetTimeInterval:self.device.device_id success:^(NSString *_start_time, NSString *_end_time) {
            start_time = _start_time;
            end_time   = _end_time;
            [weakSelf.tableView reloadData];
        } failure:^(NSString *error) {
            
        }];
        
    }

    self.titleLabel.text = @"分享视频";
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self getData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getData{
    
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    //网络连接失败
    if (![rea isReachable]){
        
        if (fullloadingView) {
            [fullloadingView showErrorMsg:HTTPERROR_CANNOTREACH];
            
        }else{
            MBALERT(HTTPERROR_CANNOTREACH);
         }
        return;
    }
 
    [self getPeople];
}

-(void)getPeople{
    NSString *url = [NSString stringWithFormat:MAINURL, URL_GET_SHARE_USERS];
    __unsafe_unretained typeof(self) weakSelf = self;
    
    
    NSString *sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"session_id"];
    
    if(!sid)return;
    
    NSDictionary *dic = [[NSDictionary alloc] initWithObjects: @[sid,self.device.device_id] forKeys:@[@"session_id",@"device_id"]];
    NSString *json  =[dic JSONString];
    
    [AWHttpTool post:url body:json success:^(id json) {
        if (json) {

            NSInteger sta = [json[@"status"] integerValue];
            
            if (sta == 0) {
                
                //清空
                if (!dataArray) {
                    dataArray = [NSMutableArray array];
                }else{
                    [dataArray removeAllObjects];
                }
                
                NSArray *shared_users = json[@"shared_users"];

                for (NSDictionary *dic in shared_users) {
                    
                    UserUnit *user = [[UserUnit alloc]init];
                    user.useruuid = dic[@"user_phoneno"];
                    [dataArray addObject:user];
                }
    
//                if (dataArray.count) {
                    [self getShareUsersHeight];
//                }

                [weakSelf.tableView reloadData];
                
            }else{
                NSString *err = json[@"msg"];
                MBALERT(err);
            }
        }
    } failure:^(NSError *error) {
        //        [hud hide:YES afterDelay:0.5];
//        [self doneLoadingTableViewData];
        
        MBALERT(HTTPERROR_DATAFAIL);
    }];

}

-(void)getShareUsersHeight{
    NSInteger rows = dataArray.count>0? (dataArray.count+2-1)/USERCOUNT_ROW +  1:
    1;
    
    shareUsers_height = rows * ShareUser_Height + (rows+1)*ShareUser_IntervalY ;

}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    
    if (section == 1) {
        return 3;
    }
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section==0?0:20;
}



- (UIView *)tableView:(UITableView *)_tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0)
        return shareUsers_height;
    
    return 60;
}



- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        static NSString *CellSUC = @"CellDHC";
        ShareUserCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellSUC];
        if (!cell) {
            cell=[[ShareUserCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellSUC];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
         }
        __weak __typeof(self)weakSelf = self;

        cell.tapBlock = ^(UserUnit*user, NSInteger index){

            if([user.useruuid isEqualToString:@"添加"]){
                UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                InputShareUserViewController *isuvc = [board instantiateViewControllerWithIdentifier:@"InputShareUserViewController"];
                isuvc.smartdevice = self.device;
                [weakSelf.navigationController pushViewController:isuvc animated:YES];
            }else if([user.useruuid isEqualToString:@"删除"]){
                
                if (dataArray.count == 0) {
                    return ;
                }
                
                AllShareUsersTableViewController *astvc = [[AllShareUsersTableViewController alloc]init];
                astvc.allArray = dataArray;
                [weakSelf.navigationController pushViewController:astvc animated:YES];
            }
            

        };
        
        cell.userArray = dataArray;
        return cell;
        
    }
 
    if (indexPath.section == 1){
        
        SettingCell *cell;

        if (indexPath.row == 2){
            
            static NSString *CellSS = @"CellSS";
            cell=[_tableView dequeueReusableCellWithIdentifier:CellSS];
            if (!cell) {
                cell=[[SwitchSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellSS];
            }
            
            ((SwitchSetCell *)cell).toggle.on=YES;
            
            cell.textLabel.text = @"开放时间";
            
        }else{
            static NSString *CellSC = @"CellSC";
            cell=[_tableView dequeueReusableCellWithIdentifier:CellSC];
            if (!cell) {
                cell=[[ShowSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellSC];
            }
            
            if (indexPath.row == 0) {
                cell.textLabel.text = @"移交管理员";
            }else{
                cell.textLabel.text = @"观看时间";
                
                if (start_time) {
                    ((ShowSetCell *)cell).contentLabel.text = [NSString stringWithFormat:@"%@ - %@", start_time,end_time];
                }

            }
        }
        cell.rowType = 3;
        return cell;
 

    }
    
    if (indexPath.section == 2){
        
        SettingCell *cell;
    
        static NSString *CellSS2 = @"CellSS2";
        cell=[_tableView dequeueReusableCellWithIdentifier:CellSS2];
        if (!cell) {
            cell=[[SettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellSS2];
        }
        
        cell.rowType = 3;
        cell.textLabel.text = @"删除群组";
        return cell;
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            
            SetShareUserAdminViewController *ssvc = [[SetShareUserAdminViewController alloc]init];
            ssvc.allArray = dataArray;
            ssvc.deviceunit = self.device;
            [self.navigationController pushViewController:ssvc animated:YES];
            
        } else if (indexPath.row == 1) {
            UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            TimeRuleViewController *trvc = [board instantiateViewControllerWithIdentifier:@"TimeRuleViewController"];
            trvc.start_time = start_time;
            trvc.end_time   = end_time;
            trvc.device_unit = self.device;
            [self.navigationController pushViewController:trvc animated:YES];
        }else{

        }

    }
 
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
